package 线程池的使用.thread;



import com.yangjicong.o2o.studey.base.common.enums.Constants;

import java.util.concurrent.*;

/**
 * 线程池
 * @author zkmac on 2019/4/28.
 */
public class ThreadPool {

    private ThreadPool(){

    }

    /**
     * 设置核心池大小
     */
    private static int corePoolSize = 2;

    /**
     * 设置线程池最大能接受多少线程
     */
    private static int  maxPoolSize = 10;

    /**
     * 当前线程数大于corePoolSize、小于maximumPoolSize时，超出corePoolSize的线程数的生命周期
     */
    private static long keepAliveTime = 2;

    /**
     * 设置时间单位，秒
     */
    private static TimeUnit timeUnit = TimeUnit.SECONDS;

    /**
     * 排队策略 放入队列
     */
    private static LinkedBlockingDeque<Runnable> linkedBlockingDeque = new LinkedBlockingDeque<Runnable>();


    private static ThreadPoolExecutor.CallerRunsPolicy callerRunsPolicy = new ThreadPoolExecutor.CallerRunsPolicy();

    /**
     * 创建线程池
     */
    public final static ThreadPoolExecutor THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(corePoolSize, maxPoolSize,
            keepAliveTime,timeUnit, linkedBlockingDeque, MarketingToolThreadFactory.defaultThreadFactory(Constants.APPLY_NAME),
            callerRunsPolicy);

    /**
     * 任务调度线程池
     */
    public final static ScheduledThreadPoolExecutor SCHEDULED_THREAD_POOL_EXECUTOR = new ScheduledThreadPoolExecutor(
            5, MarketingToolThreadFactory.defaultThreadFactory(Constants.APPLY_NAME));

    /**
     * 利用线程池中资源，启动线程
     * @param runnable
     */
    public static void execute(Runnable runnable) {
        THREAD_POOL_EXECUTOR.execute(runnable);
    }

    public static <T> T submit(Callable callable){
        Future<?> submit = THREAD_POOL_EXECUTOR.submit(callable);
        try {
            return (T) submit.get();
        } catch (InterruptedException | ExecutionException e) {
            Thread.currentThread().interrupt();
        }
        return null;
    }
}